import json


def analyze_data(input_file, output_file):
    # 初始化统计数据
    total_records = 0
    strict_consistent_count = 0
    mixed_lang_count = 0
    lang_records = {}
    model_records = {}

    # 逐行读取 JSON 文件
    with open(input_file, 'r') as file:
        for line in file:
            data = json.loads(line)
            total_records += 1

            # 统计严格一致的比例
            if data['is_strict_consistent']:
                strict_consistent_count += 1

            # 统计混合语言的比例
            if data['is_mixed_lang']:
                mixed_lang_count += 1

            # 统计各个语言的记录数和准确率
            user_set_lang = data['user_set_lang']
            if user_set_lang not in lang_records:
                lang_records[user_set_lang] = {'count': 0, 'strict_consistent': 0}
            lang_records[user_set_lang]['count'] += 1
            if data['is_strict_consistent']:
                lang_records[user_set_lang]['strict_consistent'] += 1

            # 统计各个模型的记录数和准确率
            model_name = data['model_name']
            if model_name not in model_records:
                model_records[model_name] = {'count': 0, 'strict_consistent': 0}
            model_records[model_name]['count'] += 1
            if data['is_strict_consistent']:
                model_records[model_name]['strict_consistent'] += 1

    # 计算整体准确率和混合语言占比
    overall_accuracy = (strict_consistent_count / total_records) * 100
    mixed_lang_percentage = (mixed_lang_count / total_records) * 100

    # 准备写入文件的内容
    result = [
        f"【总样本数】: {total_records}",
        f"【整体准确率】: {overall_accuracy:.2f}%",
        f"回复混合语言比例: {mixed_lang_percentage:.2f}%",
        "\n【语种维度统计结果】"
    ]

    for lang, record in lang_records.items():
        lang_accuracy = (record['strict_consistent'] / record['count']) * 100
        result.append(f"  {lang}: 样本数 {record['count']}, 准确率 {lang_accuracy:.2f}%")

    result.append("\n【模型维度统计】")
    for model, record in model_records.items():
        model_accuracy = (record['strict_consistent'] / record['count']) * 100
        result.append(f"  {model}: 样本数 {record['count']}, 准确率 {model_accuracy:.2f}%")

    # 将结果写入文件
    with open(output_file, 'w') as file:
        file.write('\n'.join(result))


# 使用函数进行数据分析
analyze_data('data.json', 'data_analysis.txt')
